package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.SetmealDao;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.dto.SetmealDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.web.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐业务层实现类
 *
 * @Name : SetmealServiceImpl
 * @Author : WuQiang
 * @Date : 2022-08-014 16:18
 * @Description : 套餐业务层实现类
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal>
        implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveWithDish(SetmealDto setmealDto) {
        //核心业务
        //套餐名称唯一性校验
        int count = this.count(Wrappers.lambdaQuery(Setmeal.class)
                .eq(Setmeal::getName, setmealDto.getName()));
        if (count > 0) {
            throw new BusinessException("套餐名已经存在，不能重复添加");
        }
        //添加套餐
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        //添加套餐菜品关系
        return setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 分页查询套餐 根据套餐名称分页查询
     *
     * @param pageNum  当前页
     * @param pageSize 页面大小
     * @param name     套擦名称
     * @return
     */
    @Override
    public Page<SetmealDto> page(Long pageNum, Long pageSize, String name) {
        //核心业务
        Page<Setmeal> ipage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), Setmeal::getName, name);
        this.page(ipage, lqw);
        Page<SetmealDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(ipage, dtoPage, "records");
        //查询所有套餐
        List<Category> categoryList = categoryService.getList(2);
        List<Setmeal> setmealList = ipage.getRecords();
        //获取页面所需数据
        List<SetmealDto> setmealDtoList = setmealList.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            //查询套餐名称
            Category categoryQuery = categoryList.stream()
                    .filter(category -> category.getId().equals(setmealDto.getCategoryId()))
                    .findFirst().get();
            setmealDto.setCategoryName(categoryQuery.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(setmealDtoList);
        return dtoPage;
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delByIds(Long[] ids) {
        //核心业务
        //判断当前套餐是否在售卖状态
        int count = this.count(Wrappers.lambdaQuery(Setmeal.class)
                .in(!ObjectUtils.isEmpty(ids), Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1));
        if (count > 0) {
            throw new BusinessException("当前套餐正在售卖中，不能删除！");
        }
        //删除逻辑
        //删除套餐
        this.removeByIds(Arrays.asList(ids));

        //删除套餐中的菜品信息
        boolean result = setmealDishService.remove(Wrappers.lambdaQuery(SetmealDish.class)
                .in(SetmealDish::getSetmealId, ids));
        return result;
    }

    /**
     * 修改套餐状态
     *
     * @param status 0:停用 1:启用
     * @param ids    套餐id
     * @return
     */
    @Override
    public Boolean updateStatus(Integer status, Long[] ids) {
        //核心业务
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Setmeal::getStatus, status)
                .in(Setmeal::getId, ids);
        return this.update(wrapper);
    }


    /**
     * 根据套餐id查询回显套餐相关信息
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDto fingById(Long id) {
        //核心业务
        //创建返回值对象
        SetmealDto setmealDto = new SetmealDto();
        Setmeal setmeal = this.getById(id);
        BeanUtils.copyProperties(setmeal, setmealDto);

        //根据套餐id查询套餐中的菜品信息
        List<SetmealDish> setmealDishList = setmealDishService.list(Wrappers.lambdaQuery(SetmealDish.class)
                .eq(SetmealDish::getSetmealId, setmealDto.getId()));
        setmealDto.setSetmealDishes(setmealDishList);
        return setmealDto;
    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateWithSetmealDish(SetmealDto setmealDto) {
        //核心业务
        //套餐名称唯一性校验
        List<Setmeal> setmealList = this.list(Wrappers.lambdaQuery(Setmeal.class)
                .eq(Setmeal::getName, setmealDto.getName()));
        if (setmealList != null || setmealList.size() > 0) {
            //排除掉自己的情况
            for (Setmeal setmeal : setmealList) {
                if (!setmeal.getId().equals(setmealDto.getId())) {
                    throw new BusinessException("当前套餐名称已经存在，请换个套餐名称后重试");
                }
            }
        }

        //修改套餐业务
        this.updateById(setmealDto);
        //套餐中的菜品，先删除后插入
        //先根据套餐id删除相关套餐与菜品关系表中的数据
        setmealDishService.remove(Wrappers.lambdaQuery(SetmealDish.class)
                .eq(SetmealDish::getSetmealId, setmealDto.getId()));
        //插入新的菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //设置套餐id
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        return setmealDishService.saveBatch(setmealDishes);
    }
}




